package com.library.gq.util;
import java.sql.*;

public class BaseDao {

    private static String driver="com.mysql.cj.jdbc.Driver"; //引擎驱动
    private static String url="jdbc:mysql://1.116.221.28:3306/book?useUnicode=true&characterEncoding=utf8";//路径
    private static String userName="root";	//数据库用户名
    private static String pwd="ybpaeee7aiNa.";		//数据库密码
    public Connection conn=null;	//连接
    public PreparedStatement ps=null;
    public ResultSet rs=null;

    /**
     * 连接
     * @return
     */
    public Connection getConn()
    {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            conn= DriverManager.getConnection(url,userName,pwd);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 通用增删改
     * @param sql
     * @param ob
     * @return
     */
    public int executeUpdate(String sql,Object... ob)
    {
        int sum=0;
        conn=getConn();
        try {
            ps=conn.prepareStatement(sql);
            for (int i = 0; i < ob.length; i++) {
                ps.setObject(i+1,ob[i]);
            }
            sum=ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            close(conn,ps,rs);
        }

        return sum;
    }
    /**
     * 查询
     * @param sql
     * @param ob
     * @return
     */
    public ResultSet executeQuery(String sql,Object... ob)
    {
        conn=getConn();
        try {
            ps=conn.prepareStatement(sql);
            if(ob!=null) {
                for (int i = 0; i < ob.length; i++) {
                    ps.setObject(i+1,ob[i]);
                }
            }
            rs=ps.executeQuery();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 关闭
     * @param conn
     * @param ps
     * @param rs
     */
    public void close(Connection conn,PreparedStatement ps,ResultSet rs)
    {
        try {
            if(rs!=null)
            {
                rs.close();
            }
            if(ps!=null)
            {
                ps.close();
            }
            if(conn!=null)
            {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
